import { inviteCode } from './user'
import { report } from './request'
import { debug } from './config'
import { imagePathOnly } from './file-utils'

// #ifdef MP
/**
 * 微信分享回调
 * @param flag true-好友 false-朋友圈
 * @param getShareInfo 获取自定义分享信息
 */
const wxShare =
  (
    flag: boolean,
    getShareInfo?: () => {
      title?: string
      imageUrl?: string
      path?: string
      query?: string
    },
  ) =>
  (e?: Page.ShareAppMessageOption): Page.CustomShareContent => {
    const pages = getCurrentPages()

    report('capsule_button_click', {
      type: flag ? 'message' : 'timeline',
      from: e?.from,
      path: pages[pages.length - 1].route,
    })

    let title = '蒜蒜' + (debug ? '（测试版）' : '')
    let imageUrl = imagePathOnly('wx-message.jpg', false)
    let path = '/pages/index/index'
    let query = '?code=' + inviteCode.value

    if (getShareInfo) {
      const info = getShareInfo()

      title = info.title || title
      imageUrl = info.imageUrl || imageUrl
      path = info.path || path
      query += info.query || ''
    }

    path += query

    return { title, imageUrl, path }
  }

/**
 * 微信收藏回调
 * @param getShareInfo 获取自定义分享信息
 */
const wxCollect =
  (
    getShareInfo?: () => {
      title?: string
      imageUrl?: string
      path?: string
      query?: string
    },
  ) =>
  (): Page.CustomFavoritesContent => {
    const pages = getCurrentPages()

    report('capsule_button_click', {
      type: 'collect',
      path: pages[pages.length - 1].route,
    })

    let title = '蒜蒜' + (debug ? '（体验版）' : '')
    let imageUrl = ''
    let query = ''

    if (getShareInfo) {
      const info = getShareInfo()

      title = info.title || title
      imageUrl = info.imageUrl || imageUrl
      query += info.query || ''
    }

    // @ts-ignore
    return { title, imageUrl, query }
  }

// #ifdef MP-WEIXIN
uni.onCopyUrl(() => {
  const pages = getCurrentPages()

  report('capsule_button_click', {
    type: 'copy_url',
    path: pages[pages.length - 1].route,
  })

  return { query: '' }
})
// #endif

export { wxShare, wxCollect }
// #endif
